import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/admin',
    component: () => import('@/components/Layout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '仪表盘', icon: 'House' }
      },
      {
        path: 'questions',
        name: 'Questions',
        component: () => import('@/views/Questions.vue'),
        meta: { title: '题库管理', icon: 'Document' }
      },
      {
        path: 'users',
        name: 'Users',
        component: () => import('@/views/Users.vue'),
        meta: { title: '用户管理', icon: 'User' }
      },
      {
        path: 'records',
        name: 'Records',
        component: () => import('@/views/Records.vue'),
        meta: { title: '考试记录', icon: 'List' }
      },
      {
        path: 'settings',
        name: 'Settings',
        component: () => import('@/views/Settings.vue'),
        meta: { title: '系统设置', icon: 'Setting' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const adminUserStr = localStorage.getItem('adminUser')
  
  if (to.meta.requiresAuth) {
    if (!adminUserStr) {
      next('/login')
      return
    }
    
    try {
      const adminUser = JSON.parse(adminUserStr)
      if (!adminUser.token) {
        localStorage.removeItem('adminUser')
        next('/login')
        return
      }
    } catch (e) {
      localStorage.removeItem('adminUser')
      next('/login')
      return
    }
  }
  
  if (to.path === '/login' && adminUserStr) {
    try {
      const adminUser = JSON.parse(adminUserStr)
      if (adminUser.token) {
        next('/admin/dashboard')
        return
      }
    } catch (e) {
      // 忽略解析错误
    }
  }
  
  next()
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 管理后台` : '管理后台'
})

export default router

